package com.visikard.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * @author  Ly Tuan Cuong
 * auto scale up image need one direction fixed, one direction wrap
 */
public class ResizableImageView extends ImageView {

	public ResizableImageView(Context context) {
		this(context, null);
	}

	public ResizableImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	public ResizableImageView (Context context, AttributeSet attrs, int defStyle){
		super(context, attrs, defStyle);
	}

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
		Drawable d = getDrawable();

		if(d!=null){
			// ceil not round - avoid thin vertical gaps along the left/right edges
			
			int width = MeasureSpec.getSize(widthMeasureSpec);
			int height = MeasureSpec.getSize(heightMeasureSpec);
			
			if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY){
				height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
				// create rect image view for crop center scale type
				if (this.getScaleType() != ScaleType.CENTER_CROP)
					setMeasuredDimension(width, height);
				else
					setMeasuredDimension(width, width);
			}
			else{
				width = (int) Math.ceil((float) height * (float) d.getIntrinsicWidth() / (float) d.getIntrinsicHeight());
				// create rect image view for crop center scale type
				if (this.getScaleType() != ScaleType.CENTER_CROP)
					setMeasuredDimension(width, height);
				else
					setMeasuredDimension(height, height);
			}
			
		}else{
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}
	}

}